/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

/**
 *
 * @author Carlos Pinheiro
 */
public class DownloadersController extends Thread
{

    private static DownloadersController dc = new DownloadersController();
    private static final int WAIT_TIME = 1000;
    private static final int THRESHOLD = 10000;

    private DownloadersController()
    {
    }

    public static DownloadersController getInstance()
    {
        return dc;
    }

    @Override
    public void run()
    {
        BandwithAllocation bwa = BandwithAllocation.getInstance();
        DownloadersLauncher dl = DownloadersLauncher.getInstance();

        try
        {
            while (!isInterrupted())
            {
                /*if (PendingQueue.getInstance().isEmpty())
                {
                    dl.removeAllDownloaders();
                }
                else
                {*/
                    long sizeDownloading = bwa.getSizeDownloading();
                    long maxDownloading = dl.getMaxBandwidthAllocation();
                    if (sizeDownloading > maxDownloading)
                    {
                        dl.decreaseDownloaders();
                    }
                    else if ((sizeDownloading + THRESHOLD) < maxDownloading)
                    {
                        dl.increaseDownloaders();
                    }
                }

                Thread.sleep(WAIT_TIME);
            //}
        }
        catch (InterruptedException ex)
        {
        }
    }
}
